<template>
  <div id="CategoriesManagePage">
    <a-flex justify="space-between">
      <h2>分类管理</h2>
      <a-button type="primary" @click="showAddModal">
        <plus-outlined />
        添加分类
      </a-button>
    </a-flex>
    <div style="margin-bottom: 16px"></div>

    <!-- 搜索表单 -->
    <a-form layout="inline" :model="searchParams" @finish="doSearch">
      <a-form-item label="分类名称" name="categoryName">
        <a-input
          v-model:value="searchParams.categoryName"
          placeholder="请输入分类名称"
          allow-clear
        />
      </a-form-item>
      <a-form-item>
        <a-button type="primary" html-type="submit">搜索</a-button>
      </a-form-item>
    </a-form>

    <div style="margin-bottom: 16px"></div>

    <!-- 分类列表 -->
    <a-table
      :columns="columns"
      :data-source="dataList"
      :pagination="pagination"
      @change="doTableChange"
    >
      <template #bodyCell="{ column, record }">
        <template v-if="column.dataIndex === 'createTime'">
          {{ dayjs(record.createTime).format('YYYY-MM-DD HH:mm:ss') }}
        </template>
        <template v-if="column.dataIndex === 'updateTime'">
          {{ dayjs(record.updateTime).format('YYYY-MM-DD HH:mm:ss') }}
        </template>
        <template v-else-if="column.key === 'action'">
          <a-space>
            <a-button type="primary" @click="showEditModal(record)">编辑</a-button>
            <a-button danger @click="showDeleteConfirm(record)">删除</a-button>
          </a-space>
        </template>
      </template>
    </a-table>

    <!-- 添加/编辑分类弹窗 -->
    <a-modal
      v-model:visible="modalVisible"
      :title="modalTitle"
      @ok="handleModalOk"
      @cancel="modalVisible = false"
    >
      <a-form :model="modalForm" layout="vertical">
        <a-form-item
          label="分类名称"
          name="categoryName"
          :rules="[{ required: true, message: '请输入分类名称' }]"
        >
          <a-input v-model:value="modalForm.categoryName" placeholder="请输入分类名称" />
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script setup lang="ts">
import { computed, createVNode, onMounted, reactive, ref } from 'vue'
import { message, Modal } from 'ant-design-vue'
import { ExclamationCircleOutlined, PlusOutlined } from '@ant-design/icons-vue'
import dayjs from 'dayjs'
import {
  addCategoriesUsingPost,
  deleteCategoriesUsingPost,
  listCategoriesByPageUsingPost,
  updateCategoriesUsingPost,
} from '@/api/categoriesController'

// 表格列定义
const columns = [
  {
    title: '分类ID',
    dataIndex: 'id',
    width: 80,
    align: 'center',
  },
  {
    title: '分类名称',
    dataIndex: 'categoryName',
    width: 200,
    align: 'center',
  },
  {
    title: '创建时间',
    dataIndex: 'createTime',
    width: 180,
    align: 'center',
  },
  {
    title: '更新时间',
    dataIndex: 'updateTime',
    width: 180,
    align: 'center',
  },
  {
    title: '操作',
    key: 'action',
    width: 180,
    align: 'center',
  },
]

// 数据列表
const dataList = ref<API.Categories[]>([])
const total = ref(0)

// 搜索参数
const searchParams = reactive<API.CategoriesQueryRequest>({
  current: 1,
  pageSize: 10,
  sortField: 'create_time',
  sortOrder: 'descend',
})

// 分页配置
const pagination = computed(() => {
  return {
    current: searchParams.current,
    pageSize: searchParams.pageSize,
    total: total.value,
    showSizeChanger: true,
    showTotal: (total: number) => `共 ${total} 条`,
  }
})

// 获取数据
const fetchData = async () => {
  const res = await listCategoriesByPageUsingPost(searchParams)
  if (res.data.code === 0 && res.data.data) {
    dataList.value = res.data.data.records ?? []
    total.value = res.data.data.total ?? 0
  } else {
    message.error('获取数据失败：' + res.data.message)
  }
}

// 搜索
const doSearch = () => {
  searchParams.current = 1
  fetchData()
}

// 表格变化处理
const doTableChange = (page: any) => {
  searchParams.current = page.current
  searchParams.pageSize = page.pageSize
  fetchData()
}

// 弹窗相关
const modalVisible = ref(false)
const modalTitle = ref('')
const modalForm = reactive<{
  id?: number
  categoryName: string
}>({
  categoryName: '',
})

// 显示添加弹窗
const showAddModal = () => {
  modalTitle.value = '添加分类'
  modalForm.id = undefined
  modalForm.categoryName = ''
  modalVisible.value = true
}

// 显示编辑弹窗
const showEditModal = (record: API.Categories) => {
  modalTitle.value = '编辑分类'
  modalForm.id = record.id
  modalForm.categoryName = record.categoryName ?? ''
  modalVisible.value = true
}

// 处理弹窗确认
const handleModalOk = async () => {
  if (!modalForm.categoryName.trim()) {
    message.warning('请输入分类名称')
    return
  }

  try {
    if (modalForm.id) {
      // 编辑模式
      const res = await updateCategoriesUsingPost({
        id: modalForm.id,
        categoryName: modalForm.categoryName.trim(),
      })
      if (res.data.code === 0) {
        message.success('更新成功')
        modalVisible.value = false
        fetchData()
      } else {
        message.error('更新失败：' + res.data.message)
      }
    } else {
      // 添加模式
      const res = await addCategoriesUsingPost({
        categoryName: modalForm.categoryName.trim(),
      })
      if (res.data.code === 0) {
        message.success('添加成功')
        modalVisible.value = false
        fetchData()
      } else {
        message.error('添加失败：' + res.data.message)
      }
    }
  } catch (error: any) {
    message.error('操作失败：' + error.message)
  }
}

// 显示删除确认框
const showDeleteConfirm = (record: API.Categories) => {
  Modal.confirm({
    title: '确认删除',
    icon: createVNode(ExclamationCircleOutlined),
    content: `确定要删除分类"${record.categoryName}"吗？删除后不可恢复！`,
    okText: '确认',
    okType: 'danger',
    cancelText: '取消',
    async onOk() {
      try {
        const res = await deleteCategoriesUsingPost({ id: record.id })
        if (res.data.code === 0) {
          message.success('删除成功')
          fetchData()
        } else {
          message.error('删除失败：' + res.data.message)
        }
      } catch (error: any) {
        message.error('删除失败：' + error.message)
      }
    },
  })
}

// 页面加载时获取数据
onMounted(() => {
  fetchData()
})
</script>

<style scoped>
#CategoriesManagePage {
  padding: 24px;
}
</style>
